package io.flutter.plugins.webviewflutter;

/**
 * Created by harlan on 2021/8/13.
 */

import android.app.Instrumentation;
import android.os.SystemClock;
import android.view.InputDevice;
import android.view.MotionEvent;

/**
 * 模拟点击事件和长按事件
 *
 */

public class TouchEventRunnable implements Runnable {
    private int x;
    private int y;

    private boolean isLongPress;

    public TouchEventRunnable(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public TouchEventRunnable(int x, int y, boolean isLongPress) {
        this.x = x;
        this.y = y;
        this.isLongPress = isLongPress;
    }

    @Override
    public void run() {
        if(isLongPress){
            longClickOnScreen(x,y);
        }else{
            onClick();
        }
    }


    private void longClickOnScreen(int x, int y) {
        final Instrumentation inst = new Instrumentation();
        try {
            long downTime = SystemClock.uptimeMillis();
            long eventTime = SystemClock.uptimeMillis();
            final MotionEvent eventDown = MotionEvent.obtain(downTime,
                    eventTime, MotionEvent.ACTION_DOWN, x, y, 0);
            eventDown.setSource(InputDevice.SOURCE_TOUCHSCREEN);
            final MotionEvent eventMove = MotionEvent.obtain(downTime, eventTime,
                    MotionEvent.ACTION_MOVE, x, y+1, 0);
            eventMove.setSource(InputDevice.SOURCE_TOUCHSCREEN);
            final MotionEvent eventUp = MotionEvent.obtain(downTime, eventTime,
                    MotionEvent.ACTION_UP, x, y, 0);
            eventUp.setSource(InputDevice.SOURCE_TOUCHSCREEN);
            inst.sendPointerSync(eventDown);
            inst.sendPointerSync(eventMove);
            try {
                Thread.sleep(650);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            inst.sendPointerSync(eventUp);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }



    private void onClick(){

        Instrumentation inst = new Instrumentation();
        inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                MotionEvent.ACTION_DOWN, x, y, 0));
        inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
                MotionEvent.ACTION_UP, x, y, 0));
        //Log.v("LOG", " x = " + x + " y = " + y);

    }
}